
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.swing.DefaultComboBoxModel;

public class PoStart extends javax.swing.JFrame implements DiscoveryListener {

    private LocalDevice local = null;
    private DiscoveryAgent agent = null;
    protected UUID uuid = new UUID(0x1101);
    private Vector devices = new Vector(), Urlconnection = new Vector();
    private StreamConnection con = null;

    /** Creates new form PoStart */
    public PoStart() {
        initComponents();
        cancel.setVisible(false);
        msg.setVisible(false);
        postart();
    }

    public void postart() {
        try {
            local = LocalDevice.getLocalDevice();
        } catch (BluetoothStateException ex) {
            msg.setVisible(true);
            msg.setText("No bluetooth Stack.");
            events.setText("No bluetooth Stack..");
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        devicecombo = new javax.swing.JComboBox();
        cancel = new javax.swing.JButton();
        events = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        msg = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        search = new javax.swing.JButton();

        setTitle("Point of Sale App");
        setFocusTraversalPolicyProvider(true);
        setLocationByPlatform(true);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Start.png"))); // NOI18N

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        devicecombo.setFont(new java.awt.Font("Arial", 0, 10));
        devicecombo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
        devicecombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                devicecomboActionPerformed(evt);
            }
        });

        cancel.setBackground(new java.awt.Color(255, 255, 255));
        cancel.setForeground(new java.awt.Color(255, 255, 255));
        cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cancel2.png"))); // NOI18N
        cancel.setToolTipText("Cancel Service Search");
        cancel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        events.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        events.setForeground(new java.awt.Color(255, 0, 0));
        events.setText("......");

        jLabel3.setFont(new java.awt.Font("Arial", 0, 10));
        jLabel3.setText("Discovered Devices");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(events, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(devicecombo, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancel))
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(devicecombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(events, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bot3.png"))); // NOI18N

        msg.setBackground(new java.awt.Color(102, 102, 102));
        msg.setFont(new java.awt.Font("Arial", 0, 10));
        msg.setForeground(new java.awt.Color(102, 102, 102));
        msg.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        msg.setText("Starting..");

        jButton2.setBackground(new java.awt.Color(0, 0, 0));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/shutd.png"))); // NOI18N
        jButton2.setToolTipText("Exit");
        jButton2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        search.setBackground(new java.awt.Color(255, 255, 255));
        search.setFont(new java.awt.Font("Tahoma", 0, 10));
        search.setText("Search");
        search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE)
                                    .addComponent(jButton2)
                                    .addContainerGap())
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap()))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addContainerGap())))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(search)
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(msg)
                        .addGap(11, 11, 11))
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)))
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void devicecomboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_devicecomboActionPerformed
        if(devicecombo.getSelectedItem()!=null){
            devicecombo.setEnabled(false);
            search.setEnabled(false);
            cancel.setVisible(true);

            String getremoteaddr = (String) devicecombo.getSelectedItem(), remoteadd = null;
            int t = getremoteaddr.indexOf("(", 0);
            remoteadd = getremoteaddr.substring(t + 1, getremoteaddr.length() - 1);
            startservicesearch(new RemoteDevice(remoteadd) {
            });
        }
}//GEN-LAST:event_devicecomboActionPerformed

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        agent.cancelServiceSearch(DiscoveryAgent.GIAC);
        devicecombo.setEnabled(true);
        search.setEnabled(true);
}//GEN-LAST:event_cancelActionPerformed

    private void searchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchActionPerformed
        if (local != null) {
            try {
                events.setText("Searching for Remote Devices....");
                devices.removeAllElements();
                Urlconnection.removeAllElements();
                devicecombo.removeAllItems();
                devicecombo.setEnabled(false);
                msg.setVisible(true);
                msg.setText("Bluetooth is enabled");
                search.setEnabled(false);
                events.setText("Bluetooth Enabled..");

                agent = local.getDiscoveryAgent();
                agent.startInquiry(DiscoveryAgent.GIAC, this);
            } catch (BluetoothStateException ex) {
            }
        } else {

            postart();
        }
}//GEN-LAST:event_searchActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        events.setText("Application is exitting..");
        System.exit(0);
}//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PoStart().setVisible(true);
            }
        });
    }
     private void startservicesearch(RemoteDevice remoteDevice) {
     UUID uuids[] = new UUID[]{uuid};
        try {
            events.setText("Searching for device servicces...." );
            agent.searchServices(null, uuids, remoteDevice, this);
             msg.setVisible(false);
               msg.setVisible(false);


        } catch (BluetoothStateException ex) {
           msg.setVisible(true);
           events.setText("Service Search Failed. Try Again." );
           events.setVisible(true);
        }
      }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JComboBox devicecombo;
    private javax.swing.JLabel events;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel msg;
    private javax.swing.JButton search;
    // End of variables declaration//GEN-END:variables

    public void deviceDiscovered(RemoteDevice remote, DeviceClass arg1) {
        events.setText("Discovering Devices....");
        if (!devices.contains(remote)) {
            try {
                String friendlyname = remote.getFriendlyName(true);
                devices.addElement(friendlyname + "(" + remote + ")");
                deviceadd(devices);
                events.setText("Device Found....");
            } catch (IOException ex) {
            }
        }
    }

    public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
        for (int i = 0; i < arg1.length; i++) {
            ServiceRecord rec = arg1[i];
            String url = rec.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            events.setText("Service Search Finished....");
            DisplayKitchen(url);
        }
    }

    public void serviceSearchCompleted(int arg0, int arg1) {
        String msg = null;
        if(arg1==SERVICE_SEARCH_COMPLETED){

        }else{
        switch (arg1) {
         case SERVICE_SEARCH_TERMINATED:
                msg = "the service search cancelled ";
                break;
            case SERVICE_SEARCH_ERROR:
                msg = "an error occurred";
                break;
            case SERVICE_SEARCH_NO_RECORDS:
                msg = "no records were found ";
                break;
            case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                msg = "the device can not be reached";
                break;
        }
     events.setText(msg);
      devicecombo.setEnabled(true);

        }
    }

    public void inquiryCompleted(int arg0) {
        if (devices.size() <= 0) {
            msg.setVisible(true);
           msg.setText("No Remote Device Found");
           events.setText("No device Found...." );
           search.setEnabled(true);
        } else {
            devicecombo.setEnabled(true);
            search.setEnabled(true);
        }
        cancel.setVisible(false);
    }

    private void deviceadd(Vector deviced) {
        if (deviced.size() <= 0) {
            msg.setText("No Remote Device Found. Try Again");
            events.setText("No Device Found....");
            search.setEnabled(true);
        } else {
            devicecombo.setModel(new DefaultComboBoxModel(deviced));
        }
    }

    private void DisplayKitchen(final String url) {
 
        try {
            con = (StreamConnection) Connector.open(url);
            this.setVisible(false);
            pos l = new pos(con);
            l.pack();
            l.setLocationRelativeTo(null);
            l.setVisible(true);
        } catch (IOException ex) {
        }

    }
}
